<?php

namespace App\Http\Controllers\Api;

use App\Libs\WeChat\WxSmallClient;
use App\Models\Activity;
use App\Models\activity_job;
use App\Models\activity_user;
use App\Models\user;
use App\Models\user_formid;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * 活动控制器
 */
class ActivityController extends Controller
{
    /**
     * 活动列表
     * @param Request $request
     */
    public function activitys(Request $request)
    {
        $page = $request->json('page', 1);
        $list = Activity::lists($page);
        fun_respon(1, $list);
    }

    /**
     * 活动详情
     */
    public function activityinfo_bak(Request $request)
    {
        $openid = $request->openid;
        $activity_id = 1;//$request->json('activity_id');
        $job_id = $request->json('job_id', 0); // 组团任务主键ID 如果是通过分享的进入有次参数

        // 默认活动状态类型--可以直接参加活动
        $activity_type = activity_job::job_type_start;
        $user_list = [];
        $face_type = 0;
        $me_job_id = 0;

        // 查询 参加自己参加活动的状态
        if (empty($job_id)) {
            $where = ['activity_id'=>$activity_id, 'openid'=>$openid, 'status'=>0];
            $user_status = activity_user::where($where)->first();
            if ($user_status) {
                $job_id = $user_status->job_id;
                // 查询此活动参与人数
                $user_list = activity_user::userlist($user_status->job_id);
                $counts = activity_user::where('job_id', $user_status->job_id)->count();
                if ($counts >= activity_user::usernumber) {
                    $activity_type = activity_job::job_type_stop;
                    $face_type = $user_status->face;
                } else { // 活动进行中
                    $activity_type = activity_job::job_type_run;
                }
            }
        } else {
            // 有分享的任务ID
            $user_list = activity_user::userlist($job_id);
            $user_list_count = count($user_list);
            $self_status = activity_user::where(['job_id'=>$job_id,'openid'=>$openid])->first();
            if ($self_status) {
                if ($user_list_count >= activity_user::usernumber) {
                    if ($self_status->status == 1) {
                        // 当前活动已经领取，查询用户是否还有正在进行中的任务
                        $self_user_curr = activity_user::where(['status'=>0,'openid'=>$openid])->first();
                        if ($self_user_curr) {
                            /*$job_id = $self_user_curr->job_id;
                            $user_list_2 = activity_user::userlist($job_id);
                            $user_list_count_2 = count($user_list_2);
                            if ($user_list_count_2 >= activity_user::usernumber) {
                                $activity_type = activity_job::job_type_stop;
                                $face_type = $self_user_curr->face;
                            } else {
                                $activity_type = activity_job::job_type_run;
                            }*/
                            $me_job_id = $self_user_curr['job_id'];
                        } else {
                            $activity_type = activity_job::job_type_start;
                            $job_id = 0;
                        }
                    } else {
                        $activity_type = activity_job::job_type_stop;
                        $face_type = $self_status->face;
                    }
                } else {
                    $me_job_id = $job_id;
                    $activity_type = activity_job::job_type_run;
                }
            } else {
                $self_user_curr = activity_user::where(['status'=>0,'openid'=>$openid])->first();
                if ($self_user_curr) {
                    $me_job_id = $self_user_curr['job_id'];
                }
                $activity_type = activity_job::job_type_run;
            }
        }

        $param = ['activity_type'=>$activity_type, 'user_list'=>$user_list, 'job_id'=>$job_id, 'me_job_id'=>$me_job_id];
        if ($param['activity_type'] == activity_job::job_type_stop) {
            switch ($face_type){
                case 1:
                    //$param['card_id'] = 'p2k0WuOovIc89UiCPu19cGcVK-rw';
                    $param['card_id'] = 'p2k0WuKwzRHVy_17Pvt68oU1X8eM';
                    break;
                case 2:
                    //$param['card_id'] = 'p2k0WuG7FXSfaV1tyJoV1uCOK4to';
                    $param['card_id'] = 'p2k0WuNqGTDGt-Dh6qrgPaoYUfKM';
                    break;
                case 3:
                    //$param['card_id'] = 'p2k0WuDbhg38JnAY9UB_YPnR_CIA';
                    $param['card_id'] = 'p2k0WuDHglyWlLObODhS87yE9ldI';
                    break;
                case 4:
                    //$param['card_id'] = 'p2k0WuNK6CF-jbStlr2nCeleyvfA';
                    $param['card_id'] = 'p2k0WuE-XrdQdh2u7m_fON8KHu8c';
                    break;
                default :
                    $param['card_id'] = '';
                    break;
            }

        } else {
            $param['card_id'] = '';
        }
        fun_respon(1, $param);
    }

    /**
     * 参与活动接口
     */
    public function joinactivity_bak(Request $request)
    {
        try {
            // 固定活动ID
            $activity_id = 1;//$request->json('activity_id', 1);
            $job_id = (int) $request->json('job_id');
            $openid = $request->openid;
            $face = $request->json('face');
            if (empty($face)) fun_respon(0, '翻牌错误');


            // 判断当前翻的面是否之前已经翻过面
            $make_act = activity_user::where(['openid'=>$openid, 'face'=>$face, 'activity_id'=>$activity_id])->first();
            if ($make_act) fun_respon(0, '您之前已经翻过这个脸了哦！');

            if (empty($job_id)) {
                // 没有任务创建新任务
                // 创建任务之前，判断自己是否有任务在进行中
                activity_job::curr_activity($openid, $activity_id, $face);
            }
            // 判断 传入的job是否可以参与活动 不能参与活动直接创建自己的新活动
            $job_user_num = activity_user::where('job_id', $job_id)->count();
            if ($job_user_num >= activity_user::usernumber) {
                activity_job::curr_activity($openid, $activity_id, $face);
            } else {
                // 查询翻面是否冲突
                $is_face = activity_user::where(['job_id'=>$job_id, 'face'=>$face])->first();
                if ($is_face) {
                    fun_respon(0, '该角色已经被翻过脸啦，请翻其他的脸吧！');
                }
                $is_join = activity_user::where(['job_id'=>$job_id, 'openid'=>$openid])->first();
                if ($is_join) {
                    fun_respon(0, '您已经翻过脸啦！');
                }
                // 判断自己是否有正在进行的job
                $self_join = activity_user::where(['status'=>0, 'openid'=>$openid])->first();
                if ($self_join) {
                    fun_respon(0, '您有参与过的活动还在进行中');
                }

                // 直接参与此活动
                $join_data = [
                    'openid' => $openid,
                    'activity_id' => $activity_id,
                    'job_id' => $job_id,
                    'face' => $face,
                ];
                $res = activity_user::insert($join_data);
                if ($res) {
                    if ($job_user_num == (activity_user::usernumber-1)) {
                        // 推送模板消息
                        $push_list = activity_user::select('openid')->where('job_id', $job_id)->get()->toArray();
                        $this->__pushtemp($push_list, $job_id);
                    }
                    fun_respon(1, '参与活动成功');
                }
                fun_respon(0, '系统繁忙，请稍后再试');
            }
        } catch (\Exception $ex) {
            fun_respon(0, $ex->getMessage());
        }
    }

    public function __pushtemp($list, $job_id)
    {
        $template_id = 't9XzxP1iF_XunJHqENE1Ontqt6bOMYHAFvfoqoVcZE8';
        //示例数据根据消息模板填充
        $data = array(
            'keyword1'=>array('value'=>'您参与的翻脸活动可以领取礼物啦','color'=>'#7167ce'),
            'keyword2'=>array('value'=>'鹰嘴脆一盒','color'=>'#7167ce'),
            'keyword3'=>array('value'=>'PavoMea','color'=>'#7167ce')
        );

        foreach ($list as $v) {
            $user = user::where('openid', $v['openid'])->first();
            if ($user) {
                $formId = user_formid::lastformid($v['openid']);
                if (!$formId) {
                    savelog('no_push_user', 'openid='.$user->openid.'&job_id='.$job_id);
                }

                $res = WxSmallClient::sendTemplate($user->openid, $data, $formId->form_id, $template_id);
                if (!isset($res['errcode']) || $res['errcode'] != 0) {
                    savelog('push_err_log', json_encode($res).'openid='.$user->openid.'&form_id='.$formId->form_id);
                }
                // 删除用过的form_id
                user_formid::where('id', $formId->id)->delete();
            }
        }

    }


    /**
     * 卡券领取成功，修改领取状态
     */
    public function getsuccess(Request $request)
    {
        try {
            $openid = $request->openid;
            $job_id = $request->json('job_id');
            $activity_id = $request->json('activity_id', 1);

            if (empty($job_id) || empty($activity_id)) {
                fun_respon(0, '缺少参数');
            }
            $where = ['id'=>$job_id, 'activity_id'=>$activity_id, 'openid'=>$openid];
            $res = activity_job::where($where)->update(['status'=>2, 'ut'=>date('Y-m-d H:i:s')]);
            if ($res) {
                fun_respon(1, '领取成功');
            }
            fun_respon(0, '领取失败');
        } catch (\Exception $ex) {
            fun_respon(0, $ex->getMessage());
        }
    }

    /**
     * 活动详情
     */
    public function activityinfo(Request $request)
    {
        fun_respon(0, '翻脸已结束，第二波活动下周见，敬请期待');
        try {
            $openid = $request->openid;
            $activity_id = 1;//$request->json('activity_id');
            $job_id = $request->json('job_id', 0); // 组团任务主键ID 如果是通过分享的进入有次参数

            // 默认活动状态类型--可以直接参加活动
            $activity_type = activity_job::job_type_start;
            $user_list = []; // 帮助列表
            $face_type = 0; // 那个卡面
            $me_job = 0; // 是否是自己创建的活动

            if ($job_id) {
                $job = activity_job::where('id', $job_id)->first();
                if (!$job) fun_respon(0, '任务不存在');
                if ($job->openid == $openid) $me_job = 1;
                $job_id = $job->id;
                // 任务总参与人列表
                $user_list = activity_user::userlist($job_id);
                if (count($user_list) >= activity_user::usernumber) {
                    $activity_type = activity_job::job_type_stop;
                    if ($job->status == activity_job::job_noget) {
                        $face_type = $job->face; // 未领取 将card_id传递出去，已领取为0
                    }
                } else {
                    $activity_type = activity_job::job_type_run;
                }
            } else {
                $job = activity_job::where(['openid'=>$openid, 'status'=>1])->first();
                if ($job) {
                    $me_job = 1;
                    $job_id = $job->id;
                    $user_list = activity_user::userlist($job->id);
                    if (count($user_list) >= activity_user::usernumber) {
                        $activity_type = activity_job::job_type_stop;
                        $face_type = $job->face; // 未领取 将card_id传递出去，已领取为0
                    } else {
                        $activity_type = activity_job::job_type_run;
                    }
                }
            }

            $param = [
                'activity_type'=>$activity_type,
                'user_list'=>$user_list,
                'job_id'=>$job_id,
                'is_me_job'=>$me_job
            ];
            if ($param['activity_type'] == activity_job::job_type_stop) {
                switch ($face_type){
                case 1:
                    $param['card_id'] = 'p2k0WuOovIc89UiCPu19cGcVK-rw';
                    //$param['card_id'] = 'p2k0WuKwzRHVy_17Pvt68oU1X8eM';
                    break;
                case 2:
                    $param['card_id'] = 'p2k0WuG7FXSfaV1tyJoV1uCOK4to';
                    //$param['card_id'] = 'p2k0WuNqGTDGt-Dh6qrgPaoYUfKM';
                    break;
                case 3:
                    $param['card_id'] = 'p2k0WuDbhg38JnAY9UB_YPnR_CIA';
                    //$param['card_id'] = 'p2k0WuDHglyWlLObODhS87yE9ldI';
                    break;
                case 4:
                    $param['card_id'] = 'p2k0WuNK6CF-jbStlr2nCeleyvfA';
                    //$param['card_id'] = 'p2k0WuE-XrdQdh2u7m_fON8KHu8c';
                    break;
                default :
                    $param['card_id'] = '';
                    break;
            }

            } else {
                $param['card_id'] = '';
            }
            fun_respon(1, $param);

        } catch (\Exception $ex) {
            fun_respon(0, $ex->getMessage());
        }
    }


    /**
     * 参加活动
     */
    public function joinactivity(Request $request)
    {
        try {
            $activity_id = 1;//$request->json('activity_id', 1);
            $job_id = (int) $request->json('job_id');
            $openid = $request->openid;
            $face = $request->json('face');
            if (empty($face)) fun_respon(0, '翻牌错误');

            // 有job_id就是好友助攻
            if ($job_id) {
                $job_info = activity_job::where('id', $job_id)->first();
                if (!$job_info) fun_respon(0, '活动未找到');
                $user_count = activity_user::where('job_id', $job_id)->count();
                if ($user_count >= activity_user::usernumber) {
                    fun_respon(0, '好友已经组团成功啦！');
                }
                // 查询我给这个好友帮助过没
                if ($job_info->openid == $openid) fun_respon(0, '当前任务自己只能翻面一次哦');
                $is_help = activity_job::help_list($job_info->openid, $openid);
                if ($is_help == true) {
                    fun_respon(0, '您之前给该好友助力过了哦！');
                }
                // 当前job的face是否翻过
                $face_valid = activity_user::where(['job_id'=>$job_id, 'face'=>$face])->first();
                if ($face_valid) fun_respon(0, '该面已经被其他好友翻过面啦！');

                $add = [
                    'job_id'=>$job_id,
                    'activity_id'=>$job_info->activity_id,
                    'openid'=>$openid,
                    'face'=>$face
                ];
                $res = activity_user::insert($add);
                if (!$res) fun_respon(0, '助力失败，请稍后重试！');
                if ($user_count == (activity_user::usernumber-1)){
                    $this->__pushtemp([['openid'=>$job_info->openid]], $job_id);
                }
                fun_respon(1, '助力好友成功啦！');
            } else {
            // 没有job_id 是自己发起job
                $where = [
                    'openid'=>$openid,
                    'activity_id'=>$activity_id,
                    'status'=>1,
                ];
                $act = activity_job::where($where)->first();
                if ($act) fun_respon(0, '您还有活动在进行中哦！');
                $where = [
                    'openid'=>$openid,
                    'face'=>$face,
                    'activity_id'=>$activity_id
                ];
                $make_act = activity_job::where($where)->first();
                if ($make_act) fun_respon(0, '您之前已经翻过这个脸了哦！');
                activity_job::createjob($openid, $activity_id, $face);
            }
        } catch (\Exception $ex) {
            //var_dump($ex->getMessage().$ex->getLine());
            fun_respon(0, $ex->getMessage());
        }
    }



}
